package com.dnake.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import com.alibaba.fastjson.JSON;
import com.dnake.Constant;
import com.dnake.WeKerApplication;
import com.dnake.db.UserBeanDao;
import com.dnake.entity.EventBusBean;
import com.dnake.entity.UserBean;
import com.dnake.misc.SysTalk;
import com.dnake.utils.ImageUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;


public class FaceService extends Service {
    public static Context mContext = null;
    private UserBeanDao mUserBeanDao;
    public FaceService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        mUserBeanDao = WeKerApplication.getContext().getDaoSession().getUserBeanDao();
        EventBus.getDefault().register(this);
    }
    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEventBus(EventBusBean eventBusBean){
        if (eventBusBean.getCode()== Constant.EVENTBUS_USER_CHANGE){
            UserBean userBean = JSON.parseObject(eventBusBean.getName(),UserBean.class);
            switch (Integer.parseInt(userBean.getType())){
                //增
                case 1:
                    updateUser(userBean);
                    break;
                //删
                case 3:
                    deleteUser(userBean);
                    break;
                //改
                case 2:
                    updateUser(userBean);
                    break;
            }
        }

    }
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEventBusUser(UserBean userBean){
        switch (Integer.parseInt(userBean.getType())){
            //增
            case 1:
                updateUser(userBean);
                break;
            //删
            case 3:
                deleteUser(userBean);
                break;
            //改
            case 2:
                updateUser(userBean);
                break;
        }

    }
    /**
     * 删除用户
     * @param userBean
     */
    private void deleteUser(UserBean userBean){
        mUserBeanDao.deleteByKey(userBean.getUserId());
        setStatus(userBean.getId());
    }
    /**
     * 更新用户
     * @param userBean
     */
    private void updateUser(UserBean userBean){
        if (mUserBeanDao.load(userBean.getUserId())==null){
            mUserBeanDao.insert(userBean);
        }else {
            mUserBeanDao.update(userBean);
        }
        setStatus(userBean.getId());
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    /**
     * 设置用户数据状态 为已成功
     * @param id
     */
    private void setStatus(String id) {
        if (!SysTalk.netState){
            return;
        }

        RequestParams params = new RequestParams(Constant.HTTP_URL + "/offline/device/user/update/status");
        params.setAsJsonContent(true);
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",id+"");
            params.setBodyContent(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onCancelled(CancelledException arg0) { }

            @Override
            public void onError(Throwable throwable, boolean arg1) {
                throwable.printStackTrace();
            }

            @Override
            public void onFinished() { }

            @Override
            public void onSuccess(String response) {
                Logger.json(response);
            }
        });
    }

}
